
import * as constant from '../constant'

import request from '../request'

import { push } from 'connected-react-router'
//字段同步
export const registFieldUpdate = (key, value) => {
    return { type: constant.USER_REGIST_FIELD, key, value }
}

// 注册提交
export const registSubmit = ({ email, username, password }) => {
    return async (dispatch, getState) => {
        try {
            // 网络请求
            // 成功 status 1
            // 失败 status 0
            // 错误 500
            const result = await request.user.regist(email, username, password)
            console.log(result);
            if (result.status === 1) {
                dispatch(push('/login'))
            } else {
                dispatch({ type: constant.USER_REGIST_RESULT, result })
            }

        } catch (error) {
            console.log(error);
            dispatch({ type: constant.USER_REGIST_RESULT, result: { message: error.message, errors: error.errors } })
        }

    }
}

//字段同步
export const loginFieldUpdate = (key, value) => {
    return { type: constant.USER_REGIST_FIELD, key, value }
}
// 登录提交
export const loginSubmit = ({ email, password }) => {
    return async (dispatch, getState) => {
        try {
            // 网络请求
            const result = await request.user.login(email, password)
            console.log(result);
            if (result.status === 1) {
                dispatch(push('/'))
            } else {
                dispatch({ type: constant.USER_REGIST_RESULT, result })
            }
        } catch (error) {
            console.log(error);
            dispatch({ type: constant.USER_REGIST_RESULT, result: { message: error.message, errors: error.errors } })
        }
    }
}

